package copy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import copy.com.R;
import copy.pojo.Employee;
import copy.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 2025 4.09
 **/

@RestController
@RequestMapping("/employee")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
//    @Autowired
//    private RedisTemplate redisTemplate;

    /**
     * 根据id 编辑员工信息
     * 需要先查数据回显
     * 再发请求update
     * 所以是两次请求 第二次请求复用了状态修改 status的接口
     */
    @GetMapping("/{id}")
    public R<Employee> idss(@PathVariable Long id) {
        Employee emp = empService.getById(id);
        return R.success(emp);
    }

    /**
     * 员工状态禁用启用以及员工账号修改
     * 参数
     * id..
     * status 0
     * 封装成实体 扩展性能更好
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        //清除缓存
        /* 动态构造key
        String key = "emp_" + page + "_666";*/
        Set<String> values = stringRedisTemplate.keys("emp_*");
        if (values != null) {
            stringRedisTemplate.delete(values);
        }

        empService.updateById(employee);
        return R.success("");
    }

    /**
     * locohost:8088/employee/page?page=1&pageSize=2
     * 员工分页查询
     *
     * @return spring默认开启@RequestParam
     */
// 未知原因 导致启动缓慢 所以暂时废弃   @Cacheable(value = "pagecache",key = "#pageSize +'_'+ #page")
    @GetMapping("/page")
    public R<Page> page(@RequestParam int page,
                        @RequestParam int pageSize, String name) {
        //动态构造key
        String key = "emp_" + page + "_666";
        String Pagea = stringRedisTemplate.opsForValue().get(key);
        if (Pagea != null) {
            Page<Employee> employeePage = JSON.parseObject(Pagea, new TypeReference<Page<Employee>>() {
            });
            return R.success(employeePage);
        }
        Page<Employee> employeePage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> query = new LambdaQueryWrapper<>();
        query.orderByDesc(Employee::getCreateTime);
        empService.page(employeePage, query);
        //page构造器对象转为Json
//        String s = JSONObject.toJSONString(employeePage);
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(employeePage),20,TimeUnit.MINUTES);
        return R.success(employeePage);
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        Set<String> values = stringRedisTemplate.keys("emp_*");
        if (values != null) {
            stringRedisTemplate.delete(values);
        }
        employee.setPassword(DigestUtils.md5DigestAsHex("666666".getBytes()));
        empService.save(employee);
        return R.success("");
    }


    /**
     * 以JSON形式传递过来的string字符串
     *
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        String pass = employee.getPassword();
        String passPlus = DigestUtils.md5DigestAsHex(pass.getBytes());
        LambdaQueryWrapper<Employee> qu = new LambdaQueryWrapper<>();
        qu.eq(Employee::getUsername, employee.getUsername());
        //select* from employee where username=? getone 是字段唯一
        Employee one = empService.getOne(qu);
        if (one == null) {
            return R.error("失败");
        }
        if (!one.getPassword().equals(passPlus)) {
            return R.error("失败");
        }
        if (one.getStatus() == 0) {
            return R.error("失败");
        }
        session.setAttribute("emp", one.getId());
        System.out.println("e");
        return R.success(one);
    }

    /**
     * 员工退登录
     *
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.removeAttribute("emp");
        return R.success("");
    }


}


/**
 * 根据id 编辑员工信息
 * 是否需要先查数据回显
 * 再发请求update
 * 所以是两次请求 第二次请求复用了状态修改的接口
 * <p>
 * 员工状态禁用启用以及员工账号修改
 * <p>
 * 员工分页查询
 * locohost:8088/employee/page?page=1&pageSize=2
 * <p>
 * 新增员工
 *
 * @param employee
 * @return 以JSON形式传递过来的string字符串
 * //简单处理员工登录
 * @param employee
 * @return 员工退登录
 * @param session
 * @return
 */
//    @GetMapping("/{id}")
/*
public R<Employee> saveById(@PathVariable Long id){
        Employee emp=empService.getById(id);
        return R.success(emp);
        }


*/
/**
 * 员工状态禁用启用以及员工账号修改
 *//*

//    @PutMapping
public R<String> status(@RequestBody Employee employee){
//        LambdaUpdateWrapper<Employee> emp = new LambdaUpdateWrapper<>();
//        emp.set(Employee::getStatus, employee.getStatus()).eq(Employee::getId, employee.getId());
//        empService.update(emp);
        empService.updateById(employee);
        return R.success("ok");
        }

*/
/**
 * 员工分页查询
 * locohost:8088/employee/page?page=1&pageSize=2
 *//*

//    @GetMapping("/page")
public R<Page> page(@RequestParam(value = "page", required = true) int page,
@RequestParam(required = false, defaultValue = "10") int pageSize,
        String name){
        Page<Employee> pageIn=new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> queryWrapper=new LambdaQueryWrapper<>();
        //注意一定要判断空值name 不参与查询
        queryWrapper.eq(name!=null,Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getCreateTime);
        empService.page(pageIn,queryWrapper);
        return R.success(pageIn);

        }

*/
/**
 * 新增员工
 *
 * @param employee
 * @return
 *//*

//    @PostMapping
public R<String> save(@RequestBody Employee employee){
        //给一个初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("888888".getBytes()));
        //元数据对象处理自动填充了数据 对于设置的非空字段
        empService.save(employee);
        return R.success("新增员工成功");
        }


*/
/**
 * 以JSON形式传递过来的string字符串
 * //简单处理员工登录
 *
 * @param employee
 * @return
 *//*

//    @PostMapping("/login")
public R<Employee> login(@RequestBody Employee employee,HttpSession session){
        String pass=employee.getPassword();
        String passPlus=DigestUtils.md5DigestAsHex(pass.getBytes());
        LambdaQueryWrapper<Employee> qu=new LambdaQueryWrapper<>();
        qu.eq(Employee::getUsername,employee.getUsername());
        Employee one=empService.getOne(qu);
        if(one==null){
        return R.error("失败");
        }
        if(!one.getPassword().equals(passPlus)){
        return R.error("失败");


        }
        if(one.getStatus()==0){
        return R.error("失败");

        }
        session.setAttribute("emp",one.getId());


        return R.success(one);

        }

*/
/**
 * 员工退登录
 *
 * @param session
 * @return
 *//*

//    @PostMapping("/logout")
public R<String> logout(HttpSession session){
        session.removeAttribute("emp");
        return R.success("code1");
        }
        }
*/
